package com.WJY.controller;


import com.WJY.pojo.Flower;
import com.WJY.service.FlowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/MyFlower")
@CrossOrigin
public class FlowerController {

    private R success(String msg) {
        return new R(200, msg);
    }

    ;

    private R success(Object data) {
        return new R(200, data);
    }

    ;

    private R failure(String msg) {
        return new R(500, msg);
    }

    ;

    @Autowired
    private FlowerService flowerService;

    @GetMapping
    public R queryFlowerList() {
        List<Flower> list = flowerService.queryFlowerList();
        return list != null && !list.isEmpty() ? success(list) : failure("暂无内容");
    }

    @GetMapping("/{id}")
    public R queryFlowerById(@PathVariable String id) {
        Flower flower = flowerService.queryFlowerById(Integer.parseInt(id));
        return flower != null ? success(flower) : failure("无编号为" + id + "的花");
    }

    @GetMapping(params = "name")
    public R queryFlowerByName(String name) {
        List<Flower> list = flowerService.queryFlowerByName(name);
        return list != null && !list.isEmpty() ? success(list) : failure("无名字带" + name + "字的花");
    }

    @DeleteMapping("/{id}")
    public R delFlowerById(@PathVariable String id) {
        int i = flowerService.delFlowerById(Integer.parseInt(id));
        return i>0?success("删除成功") : failure("删除失败");
    }

    @PostMapping
    public R addFlower(@RequestBody Flower flower) {
        int i = flowerService.addFlower(flower);
        return i>0?success("添加成功") : failure("添加失败");
    }

    @PutMapping
    public R updateFlower(@RequestBody Flower flower) {
        int i = flowerService.updateFlower(flower);
        return i>0?success("更新成功") : failure("更新失败");
    }
}
